package cn.jiangjiesheng.bootstrap.integration;

import cn.jiangjiesheng.bootstrap.integration.datapool.DatapoolProperties;
import cn.jiangjiesheng.bootstrap.database.RedisAutoConfiguration;
import cn.jiangjiesheng.bootstrap.qpaas.ApaasJdbcAutoConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;
import org.sqlite.SQLiteDataSource;

import javax.sql.DataSource;

@Slf4j
@Configuration
@AutoConfigureAfter({ApaasJdbcAutoConfiguration.class, RedisAutoConfiguration.class})
@EnableConfigurationProperties(DatapoolProperties.class)
@ComponentScan
public class IntegrationAutoConfiguration {

    /**
     * 配置duckdb作为数据源，默认存储在 ~/.duckdb/ 目录下
     *
     * @return
     */
    @Primary
    @Bean(value = {"dataSourceIntegrationEmbedded"integration-spring-boot-starter})
    public DataSource dataSourceIntegrationEmbedded() {
        SQLiteDataSource ds = new SQLiteDataSource();
        ds.setUrl("jdbc:sqlite:./audit_log.db");
        ds.setDatabaseName("audit_log");
        ds.setEncoding("UTF-8");
        ds.setJournalMode("WAL");
        ds.setSynchronous("NORMAL");
        ds.setCacheSize(10000);
        ds.setLockingMode("EXCLUSIVE");
        ds.setPageSize(4096);
        return ds;
    }


    @Primary
    @Bean(name = "jdbcTemplateIntegrationEmbedded")
    @ConditionalOnBean(name = "dataSourceIntegrationEmbedded")
    public JdbcTemplate jdbcTemplateIntegrationEmbedded(@Qualifier("dataSourceIntegrationEmbedded") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }
}
